/* eslint-disable vue/no-template-shadow */
<template>
  <a-modal
    title="编辑违章信息"
    :width="1400"
    :maxHeight="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-divider orientation="left" style="font-weight: bold; margin-top: -10px">
        <a-icon type="profile" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon>基本信息
      </a-divider>
      <a-row :gutter="24">
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="检查人员"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input placeholder="请输入检查人员" v-decorator="['userName']" disabled/>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input placeholder="请输入检查类型" v-decorator="['check_Type']"/>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['checkOrganizationId']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['checkTypeCode']" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="检查类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择检查类型" v-decorator="['check_Type',{ rules:[{ required: true, message: '请选择检查类型！'}]}]" @change="choosecheckSpecialty(item)">
                <a-select-option v-for="item in checkSpecialData" :key="item.id" :value="item.item">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form" >
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['qhseXyViolationId']" />
            </a-form-item>
            <a-form-item
              label="检查时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-date-picker
                placeholder="选择日期"
                show-time
                :showToday="true"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="checkTime"
                @change="handleChangeTime"/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form" >
            <a-form-item
              label="录入时间"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input v-model="enterTime" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              style="display: none;"
            >
              <a-select allow-clear placeholder="请选择数据来源" v-decorator="['enterSys']">
                <!-- <a-select-option v-for="(item) in workSpecialData" :key="item.id" :value="item.specialty" @click="chooseWorkSpecialty(item)">{{ item.specialty }}</a-select-option> -->
              </a-select>
            </a-form-item>
            <a-form-item
              label="属地单位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-tree-select
                v-model="organizationName"
                allowClear
                showSearch
                style="width: 100%;"
                tree-node-filter-prop="title"
                :treeData="QHSEOrganizationTree"
                v-if="QHSEOrganizationTree.length"
                :defaultExpandAll="true"
                :replaceFields="replaceFields"
                placeholder="请选择属地单位"
                @change="handleOrganizationSelectChange"
                :title="organizationName"
              >
              </a-tree-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="作业专业"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择作业专业" v-decorator="['workSpecialty',{ rules:[{ required: true, message: '请选择作业专业！'}]}]" @change="handleZYZYSelectChange">
                <a-select-option v-for="item in QHSEKeyWorkSpecialtyList" :key="item.id" :value="item.specialty" :code="item.specialtyCode">{{
                  item.specialty
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['workSpecialtyCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="作业项目"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input placeholder="请输入作业项目" v-decorator="['workItem',{ rules:[{ required: true, message: '请输入作业项目！'}]}]"/>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-divider orientation="left" style="font-weight: bold; margin-top: -10px">
        <a-icon type="info-circle" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon> 关键作业信息
      </a-divider>
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="关键作业类型"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-select allow-clear placeholder="请选择关键作业类型" v-decorator="['workType']" @change="handleKeyWorkTypeSelectChange">
                <a-select-option v-for="item in KeyWorkTypeList" :key="item.id" :value="item.workType" :code="item.workTypeCode">{{
                  item.workType
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['keyWorkCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="12" >
          <a-form :form="form">
            <a-form-item
              label="关键作业内容"
              :labelCol="{ sm: { span: 4 } }"
              :wrapperCol="{ sm: { span: 20 } }"
            >
              <a-select allow-clear show-search placeholder="请选择关键作业内容" v-decorator="['workContent']" @change="handleKeyWorkContentSelectChange">
                <a-select-option v-for="item in KeyWorkContentList" :key="item.id" :value="item.workContent" :rk="item.workRisk">{{
                  item.workContent
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="作业风险等级"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input placeholder="请输入作业风险等级" v-decorator="['workRisk']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-divider orientation="left" style="font-weight: bold; margin-top: -10px">
        <a-icon type="user" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon> 相关方人员</a-divider>
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="相关方人员"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input
                suffix-icon="down"
                v-decorator="['violationUserName',{ rules:[{ required: true, message: '请输入相关方人员！'}]}]"
                allow-clear
                ref="input"
                placeholder="请输入相关方人员姓名"/>
              <a-modal
                style="margin-top:-50px"
                @cancel="handleModalCancel"
                :visible="Modalvisible"
                :width="1300"
                :height="850"
              >
                <template #footer>
                  <a-button type="default" @click="handleModalCancel">取消</a-button>
                </template>
              </a-modal>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="人员单位(相关方公司)"
              :labelCol="{ sm: { span: 12 } }"
              :wrapperCol="{ sm: { span: 12 } }"
              required
            >
              <a-input
                v-decorator="['violationUserDepart']"
                placeholder="请输入相关方公司"
                allow-clear/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              style="display: none;"
            >
              <a-select allow-clear placeholder="请选择数据来源" v-decorator="['enterSys']">
                <!-- <a-select-option v-for="(item) in workSpecialData" :key="item.id" :value="item.specialty" @click="chooseWorkSpecialty(item)">{{ item.specialty }}</a-select-option> -->
              </a-select>
            </a-form-item>
            <a-form-item
              label="发包单位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-tree-select
                v-model="contractingUnitName"
                allowClear
                showSearch
                style="width: 100%;"
                tree-node-filter-prop="title"
                :treeData="unitTree"
                v-if="unitTree.length"
                :defaultExpandAll="true"
                :replaceFields="replaceFields"
                placeholder="请选择发包单位"
                @change="handlefbOrganizationSelectChange"
                :title="contractingUnitName"
              >
              </a-tree-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="位置区域"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select v-decorator="['location',{ rules:[{ required: true, message: '请选择位置区域！'}]}]" allow-clear placeholder="请选择位置区域">
                <a-select-option v-for="item in LocationList" :key="item.id" :value="item.location" @click="chooseLoc(item)">{{
                  item.location
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['locationCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6" >
          <a-form :form="form">
            <a-form-item
              label="用工性质"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select
                allow-clear
                read-only
                placeholder="请选择用工性质"
                @change="handleEmployeeTypeChange"
                v-decorator="['employeeType',{ rules:[{ required: true, message: '请选择用工性质！'}]}]"
              >
                <a-select-option v-for="item in QHSEYGXZList" :key="item.id" :value="item.item" @click="chooseEmp(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['employeeTypeCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="工号/身份证号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input
                v-decorator="['erp']"
                placeholder="请输入工号/身份证号"
                allow-clear/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="违章岗位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择违章岗位" v-decorator="['position',{ rules:[{ required: true, message: '请选择违章岗位！'}]}]">
                <a-select-option v-for="item in PositionList" :key="item.id" :value="item.position" @click="choosePos(item)">{{
                  item.position
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['positionCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="年龄"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-select allow-clear placeholder="请选择年龄" v-decorator="['age',{ rules:[{ required: false, message: '请选择年龄！'}]}]">
                <a-select-option v-for="item in QHSEAgeList" :key="item.id" :value="item.item" @click="chooseAge(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['ageCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="工龄"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-select allow-clear placeholder="请选择工龄" v-decorator="['workYears',{ rules:[{ required: false, message: '请选择工龄！'}]}]">
                <a-select-option v-for="item in QHSEGLList" :key="item.id" :value="item.item" @click="chooseWorkYears(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['workYearsCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-divider orientation="left" style="font-weight: bold; margin-top: -10px">
        <a-icon type="exclamation-circle" style="margin-right: 8px;color:rgb(13, 158, 243)"></a-icon> 违章信息</a-divider>
      <a-row :gutter="24">
        <a-col :span="18">
          <a-form :form="form">
            <a-form-item
              label="违章条款"
              :labelCol="labelCol_A"
              :wrapperCol="wrapperCol_A"
              style="width: 107.2%; margin-left: -27px"
              required
            >
              <a-select allow-clear show-search placeholder="请输入关键字段选择违章条款" v-decorator="['violationClause',{ rules:[{ required: true, message: '请输入关键字段选择违章条款！'}]}]">
                <a-select-option v-for="item in violationClauseList" :key="item.generalSpecialtyId" :value="item.description" @click="chooseVioClause(item)">{{
                  item.description
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
            >
              <a-radio-group v-decorator="['violationTypeCategory']">
                <a-radio value="通用违章" style="margin-left: 20px">通用违章</a-radio>
                <a-radio value="专业违章" style="margin-left: -10px">专业违章</a-radio>
                <a-radio value="其他" style="margin-left: -10px">其他</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="18" >
          <a-form :form="form">
            <a-form-item
              label="违章描述"
              :labelCol="labelCol_A"
              :wrapperCol="wrapperCol_A"
              style="width: 107.2%; margin-left: -27px"
              required
            >
              <a-textarea
                v-decorator="['description',{ rules:[{ required: true, message: '请输入违章描述！'}]}]"
                placeholder="请输入违章描述"
                :rows="2"
                :span="40"
              />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="违章性质"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择违章性质" v-decorator="['violationType',{ rules:[{ required: true, message: '请选择违章性质！'}]}]" @change="handleViolationTypeSelectChange">
                <a-select-option
                  v-for="item in ViolationTypeList"
                  :key="item.violationTypeId"
                  :value="item.violationType"
                  :sc="item.score"
                  :fine="item.fine"
                  :vtc="item.violationTypeCode">{{
                    item.violationType
                  }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['violationTypeCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <!-- <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="记分"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input placeholder="请输入记分分数" v-decorator="['score',{ rules:[{ required: true, message: '请输入记分！'}]}]"/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="罚款"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-input placeholder="请输入罚款" v-decorator="['fine',{ rules:[{ required: true, message: '请输入罚款！'}]}]"/>
            </a-form-item>
          </a-form>
        </a-col> -->
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="违章类别"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-tree-select
                v-model="violationCategory"
                allowClear
                showSearch
                tree-node-filter-prop="title"
                v-if="QHSEViolationCategoryLBTree.length"
                :treeData="QHSEViolationCategoryLBTree"
                :defaultExpandAll="true"
                :replaceFields="replaceFields"
                placeholder="请选择违章类别"
                @change="handleViolationCategorySelectChange"
                :title="violationCategory"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['violationCateId']" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="对应体系要素"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <!-- <a-input placeholder="请选择对应要素体系" v-decorator="['hseElement']" disabled/> -->
              <a-select allow-clear placeholder="请选择对应体系要素" v-decorator="['hseElement']">
                <a-select-option v-for="item in ViolationHSEList" :key="item.id" :value="item.item" @click="chooseHse(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['hseCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="原因分析"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select v-decorator="['causeAnalysis',{ rules:[{ required: true, message: '请选择原因分析！'}]}]" allow-clear placeholder="请选择原因分析">
                <a-select-option v-for="item in QHSEYYFXList" :key="item.id" :value="item.item" @click="chooseCause(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['clauseAnalysisCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="对应安全沟通"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <!-- <a-input placeholder="请选择对应安全沟通" v-decorator="['observeComm']" disabled/> -->
              <a-select allow-clear placeholder="请选择对应安全沟通" v-decorator="['observeComm']">
                <a-select-option v-for="item in ViolationCategoryObsList" :key="item.id" :value="item.item1 + ';' + item.item2">{{
                  item.item1
                }};{{ item.item2 }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="归属部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择归属部门" v-decorator="['directDepartment',{ rules:[{ required: true, message: '请选择归属部门！'}]}]">
                <a-select-option v-for="item in QHSEGSBMList" :key="item.id" :value="item.item" @click="chooseDepart(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['departmentCode']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['userId']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['pic']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['enterTime']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-model="organizationId" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['violationUserId']" />
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['checkDate',{ rules:[{ required: true, message: '请选择检查时间！'}]}]" />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="6">
          <a-form :form="form">
            <a-form-item
              label="可能后果"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              required
            >
              <a-select allow-clear placeholder="请选择可能后果" v-decorator="['potentialConsequence',{ rules:[{ required: true, message: '请选择可能后果！'}]}]">
                <a-select-option v-for="item in QHSEKNHGList" :key="item.id" :value="item.item" @click="chooseConsequence(item)">{{
                  item.item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              style="display: none;"
            >
              <a-input v-decorator="['consequencesCode']" disabled/>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row style="margin-bottom: -50px">
        <a-col :span="12">
          <a-form :form="form">
            <a-form-item
              label="图片"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
              style="margin-left: -188px">
              <a-upload
                name="file"
                list-type="picture-card"
                :file-list="fileList"
                :showUploadList="true"
                data-type="jpg|png|jpeg|JPG|PNG|JPEG"
                ref="Pics"
                :before-upload="beforeUpload"
                @change="handlePicChange"
                :remove="handleRemove"
                @preview="handlePreview"
                :customRequest="customRequest"
                style="margin-left: 10px"
                multiple
              >
                <div v-if="showLoader" class="spinner"></div>
                <div id="container" v-if="fileList.length < 4 && !showLoader">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handlePicCancel">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-spin>
  </a-modal>
</template>
<script>
  import moment from 'moment'
  import Exif from 'exif-js'
  import { getQHSEOrganizationTree, getQHSELocationPage, getQHSEPositionPage } from '@/api/modular/system/QHSEOrganization'
  import { QHSEXyCorssViolationDetail, QHSECrossViolationEdit, getQHSEXyViolationTypeList, getQHSEViolationHSEList } from '@/api/modular/system/QHSEXyViolation'
  import { getQHSEViolationCategoryLBTree, getQHSEViolationCategoryObsList, getQHSEViolationCategoryHSEList } from '@/api/modular/system/QHSEViolationCategory'
  import { getQHSEKeyWorkSpecialtyList, getQHSEKeyWorkTypePage, getQHSEKeyWorkContentPage } from '@/api/modular/system/QHSEKeyWork'
  import {
    getQHSEKNHGList,
    getQHSEYYFXList,
    getQHSEGSBMList,
    getQHSEAgeList,
    getQHSEGLList,
    getQHSEYGXZList,
    getCheckTypeList
  } from '@/api/modular/system/QHSEDictionary'
  import { getSpecialtyVioClause, getSpecialtyVioClauseAssocition, getViolationUserNameKid, getUnitTree1 } from '@/api/modular/system/violationManage'
  import { DatePicker, TreeSelect, Select, Input, Upload } from 'ant-design-vue'
  import { STable, XCard, XDown } from '@/components'
  import { mapGetters } from 'vuex'
  function getBase64 (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }
  async function readFileAsync(file) {
    const reader = new FileReader()
    if (file.originFileObj !== undefined) {
      reader.readAsDataURL(file.originFileObj)
      return new Promise((resolve, reject) => {
        reader.onload = function () {
          const base64String = reader.result.split(',')[1]
          resolve({ name: file.name, base64Content: base64String })
        }
        reader.onerror = function () {
          reject(new Error('读取失败'))
        }
      })
    } else {
      const parts = file.url.split(',')
      const base64String = parts[1]
      return { name: file.name, base64Content: base64String }
    }
  }
  async function convertFilesToArrayAsync(files) {
    const outputArray = []
    for (const file of files) {
      const output = await readFileAsync(file)
      // 在这里对输出对象进行进一步处理或者使用
      // console.log('output----', output)
      outputArray.push(output)
    }
    return outputArray
  }
  // 异步加载图片
  function loadImageAsync(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        const image = new Image()
        image.onload = () => resolve(image)
        image.onerror = reject
        image.src = e.target.result
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    })
  }
  export default {
    components: {
      XDown,
      XCard,
      STable,
      DatePicker,
      TreeSelect,
      Select,
      Input,
      Upload
    },
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        labelCol_A: {
          xs: { span: 12 },
          sm: { span: 3 }
        },
        wrapperCol_A: {
          xs: { span: 36 },
          sm: { span: 20 }
        },
        labelCol_S: {
          xs: { span: 12 },
          sm: { span: 6 }
        },
        wrapperCol_S: {
          xs: { span: 20 },
          sm: { span: 13 }
        },
        count: 1,
        visible: false,
        confirmLoading: false,
        data: [],
        replaceFields: {
          children: 'children',
          title: 'title',
          key: 'id',
          value: 'id'
        },
        secondOraName: {
          id: ''
        },
        form: this.$form.createForm(this),
        QHSEOrganizationTree: [],
        QHSEfbOrganizationTree: [],
        QHSEViolationCategoryLBTree: [],
        QHSEKNHGList: [],
        QHSEYYFXList: [],
        QHSEGSBMList: [],
        QHSEAgeList: [],
        QHSEGLList: [],
        QHSEYGXZList: [],
        QHSEKeyWorkSpecialtyList: [],
        checkSpecialData: [],
        KeyWorkTypeList: [],
        KeyWorkContentList: [],
        LocationList: [],
        PositionList: [],
        ViolationTypeList: [],
        ViolationCategoryHSEList: [],
        ViolationCategoryObsList: [],
        ViolationHSEList: [],
        vtc: '',
        spc: '',
        violationClauseList: [],
        selectedName: null,
        peopleList: [],
        Modalvisible: false,
        workSpecialtyValue: '',
        violationTypeValue: '',
        workTypeValue: '',
        violationClauseValue: '',
        violationCategory: '',
        organizationId: '',
        organizationName: '',
        contractingUnitName: '',
        contractingUnitId: '',
        files: [],
        previewVisible: false,
        previewImage: '',
        flag: true,
        fileList: [],
        showLoader: false,
        violationUserId: null,
        checkTime: null,
        enterTime: null,
        unitTree: [],
        valId: true, // 身份证号格式校验,
        fabaotree: {
          id: '00'
        }
      }
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    methods: {
      moment,
      handleEmployeeTypeChange(value) {
        if (value === '承包商员工') {
          this.form.setFieldsValue({ erp: '', violationUserId: '', violationUserDepart: '', violationUserName: '' })
          this.violationUserId = ''
          // 调用校验身份证号的方法
          // this.validateIDCard()
        }
      },
      validateIDCard() {
        // 正则表达式验证身份证号码格式
        if (this.form.getFieldValue('employeeType') === '承包商员工') {
          var regExp = /(^\d{17}(\d|X|x)$)/
          if (!regExp.test(this.form.getFieldValue('erp'))) {
            this.valId = false
            this.$message.error('身份证号格式错误')
          } else {
            this.valId = true
          }
        } else {
          this.valId = true
        }
      },
      // 关闭模态框（图片预览）
      handlePicCancel () {
        this.previewImage = ''
        this.previewVisible = false
      },
      customRequest(option) {
      },
      // 打开模态框（图片预览）
      async handlePreview (file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      // 删除照片
      async handleRemove (file) {
        const index = this.fileList.indexOf(file)
        const newFileList = this.fileList.slice()
        newFileList.splice(index, 1)
        this.fileList = newFileList
        this.flag = false
        const outputArray = await convertFilesToArrayAsync(this.fileList)
        // 最终得到的 outputArray 数组包含多个输出对象
        // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
        const resultArray = outputArray.map(({ name, base64Content }) => ({
          name,
          base64Content
        }))
        // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
        this.files = resultArray
      },
      // 压缩并上传文件
      async compressAndUpload(file) {
        try {
          this.showLoader = true
          const image = await loadImageAsync(file) // 加载图片
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          // 调整图片尺寸
          const maxWidth = 800
          const maxHeight = 600
          let width = image.width
          let height = image.height
          if (width > maxWidth || height > maxHeight) {
            const ratio = Math.min(maxWidth / width, maxHeight / height)
            width *= ratio
            height *= ratio
          }
          // 根据目标文件大小调整压缩质量
          const maxSizeInBytes = 2 * 1024 * 1024 // 2MB
          let compressedFile = {}
          let quality = 0.9 // 初始压缩质量
          let compressedSize = Infinity
          // 迭代压缩直到文件大小符合要求
          while (compressedSize > maxSizeInBytes && quality > 0) {
            canvas.width = width
            canvas.height = height
            ctx.clearRect(0, 0, width, height)
            ctx.drawImage(image, 0, 0, width, height)
            // 将 canvas 转为 Blob 对象，并获取文件大小
            const blob = await new Promise((resolve) => {
              canvas.toBlob((blob) => {
                resolve(blob)
              }, file.type, quality)
            })
            compressedFile = new File([blob], file.name, {
              type: file.type,
              lastModified: Date.now()
            })
            compressedSize = compressedFile.size
            // 降低压缩质量
            quality -= 0.1
          }
          const uid = 'vc-upload-' + compressedFile.lastModified + '-' + compressedFile.name.split('.')[0]
          compressedFile.uid = uid
          this.showLoader = false
          // console.log('compressedFile', compressedFile)
          return compressedFile // 解析 Promise 并将结果传递出去
        } catch (error) {
          throw error // 如果发生错误，则将错误传递出去
        }
      },
      // 上传图片之前的校验
      async beforeUpload(file) {
        // console.log('这里是 beforeUpload')
        const type = this.$refs.Pics.$attrs['data-type']
        return new Promise((resolve, reject) => {
          // 校验文件类型
          const exName = file.name.split('.')[1]
          if (!type.includes(exName)) {
            this.$message.error('请检查文件类型,只允许上传图片文件')
            const error = new Error('请检查文件类型，只允许上传图片文件')
            reject(error)
          } else if (file.size / 1024 / 1024 > 2) {
            // console.log('file:', file)
              this.compressAndUpload(file)
              .then((compressedFile) => {
                // 处理 compressedFile
                // console.log('compressedFile:', compressedFile)
                file = compressedFile
                resolve(file)
              })
              .catch((error) => {
                // 处理错误
                reject(error)
              })
              // const error = new Error('上传文件大小不能超过2MB')
              // reject(error)
          } else {
            let picTime = false
            return new Promise((resolve, reject) => {
              Exif.getData(file, function() {
                const exifData = Exif.getAllTags(this)
                let dateTimeOriginal = exifData.DateTimeOriginal
                const dateTime = exifData.DateTime
                if (!dateTimeOriginal && dateTime) {
                  dateTimeOriginal = dateTime
                }
                if (exifData && dateTimeOriginal) {
                  // console.log('dateTimeOriginal', dateTimeOriginal)
                  picTime = true
                } else {
                  picTime = false
                }
                resolve(picTime) // 返回 picTime 的值到 Promise 的 resolve 函数
              })
            }).then(result => {
              resolve(file)
              // if (result) {
              //   // console.log('图片有拍摄时间')
              //   resolve(file)
              //   // 执行图片有拍摄时间时的操作
              // } else {
              //   this.$message.error('该图片没有拍摄时间')
              //   // console.log('图片没有拍摄时间')
              //   // 执行图片没有拍摄时间时的操作
              // }
            }).catch(error => {
              console.error(error)
            })
          }
        })
      },
      // 上传图片方法
      async handlePicChange (file) {
        // 当删除的时候会触发onchange事件 因此使用flag控制onchange事件
        if (this.fileList.length >= 4) {
          this.$message.warning('最多只能选择4张图片')
        }
        if (this.flag === true) {
          file.file.status = 'done'
          const formData = new FormData()
          formData.append('file', file.file)
          this.fileList = file.fileList
          // 假设 this.fileList 是包含多个文件对象的数组
          const outputArray = await convertFilesToArrayAsync(this.fileList)
          // 最终得到的 outputArray 数组包含多个输出对象
          // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
          const resultArray = outputArray.map(({ name, base64Content }) => ({
            name,
            base64Content
          }))
          this.files = resultArray
          // const last = resultArray[resultArray.length - 1]
          // vioComparePic(last).then(res => {
          //   // console.log(res.data)
          //   if (res.data) {
          //     this.$message.error('图片重复')
          //     this.fileList.pop()
          //   } else {
          //     // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
          //     this.files = resultArray
          //   }
          // })
        } else {
          this.flag = true
        }
        // console.log('this.files', this.files)
      },
      getQHSEKNHGList(text) {
        getQHSEKNHGList().then((res) => {
          this.QHSEKNHGList = res.data
        })
      },
      getQHSEAgeList(text) {
        getQHSEAgeList().then((res) => {
          this.QHSEAgeList = res.data
        })
      },
      getQHSEYGXZList(text) {
        getQHSEYGXZList().then((res) => {
          this.QHSEYGXZList = res.data
        })
      },
      getQHSEGSBMList(text) {
        getQHSEGSBMList().then((res) => {
          this.QHSEGSBMList = res.data
        })
      },
      getQHSEYYFXList(text) {
        getQHSEYYFXList().then((res) => {
          this.QHSEYYFXList = res.data
        })
      },
      getQHSEGLList(text) {
        getQHSEGLList().then((res) => {
          this.QHSEGLList = res.data
        })
      },
      getCheckTypeList() {
        getCheckTypeList().then(res => {
            this.checkSpecialData = res.data
            // console.log(this.checkSpecialData)
        })
      },
      getQHSEKeyWorkSpecialtyList(text) {
        getQHSEKeyWorkSpecialtyList().then((res) => {
          this.QHSEKeyWorkSpecialtyList = res.data
          const option = this.QHSEKeyWorkSpecialtyList.find((opt) => opt.specialty === this.workSpecialtyValue)
          if (option !== undefined) {
            getQHSEKeyWorkTypePage({ 'code': option.specialtyCode }).then(res => {
              this.KeyWorkTypeList = res.data.rows
              const value = this.form.getFieldValue('workType')
              if (value !== null && value !== undefined) {
                const option2 = this.KeyWorkTypeList.find((opt) => opt.workType === this.workTypeValue)
                if (option2 !== undefined) {
                  // console.log('option2', option2)
                  getQHSEKeyWorkContentPage({ 'code': option2.workTypeCode }).then(res => {
                    this.KeyWorkContentList = res.data.rows
                  })
                }
              }
            })
            getQHSELocationPage({ 'code': option.specialtyCode }).then(res => {
              this.LocationList = res.data.rows
            })
            getQHSEPositionPage({ 'code': option.specialtyCode }).then(res => {
              this.PositionList = res.data.rows
            })
            this.spc = option.specialtyCode
          }
        })
      },
      getQHSEXyViolationTypeList(text) {
        getQHSEXyViolationTypeList().then((res) => {
          this.ViolationTypeList = res.data
          // const option = this.ViolationTypeList.find((opt) => opt.violationType === this.violationTypeValue)
          // const option2 = this.QHSEKeyWorkSpecialtyList.find((opt) => opt.specialty === this.workSpecialtyValue)
          // if (option !== undefined) {
          //   this.vtc = option.violationTypeCode
            // const rvtcv = this.form.getFieldValue('violationTypeCategory')
            // if (rvtcv === '专业违章') {
            //   this.spc = option2.specialtyCode
            //   console.log('spc:', this.spc)
            //   if (this.spc && this.vtc) {
            //     getQHSEXySpecialtyViolation({ 'ViolationTypeCode': this.vtc, 'SpecialtyCode': this.spc }).then(res => {
            //       this.violationClauseList = res.data.rows
            //     })
            //   } else {
            //     this.form.setFieldsValue({ violationClause: '' })
            //     this.violationClauseList = []
            //   }
            // } else if (rvtcv === '通用违章') {
            //   getQHSEXyGeneralViolation({ 'ViolationTypeCode': this.vtc }).then(res => {
            //     this.violationClauseList = res.data.rows
            //   })
            // } else {
            //   this.violationClauseList = []
            // }
          // }
        })
      },
      getQHSEViolationHSEList(text) {
        getQHSEViolationHSEList().then((res) => {
          this.ViolationHSEList = res.data
        })
      },
      getQHSEOrganizationTree () {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('tree:', res.data)
        this.treeLoading = false
        if (!res.success) {
          return
        }
        this.QHSEOrganizationTree = res.data
        })
      },
      getUnitTree () {
          // console.log(this.secondOraName)
          getUnitTree1(Object.assign(this.fabaotree)).then(res => {
            this.treeLoading = false
            this.unitTree = res.data
            // console.log(this.unitTree)
          })
          // this.visible = false
        },
      getQHSEViolationCategoryLBTree() {
        getQHSEViolationCategoryLBTree().then((res) => {
          this.formLoading = false
          if (!res.success) {
            this.QHSEViolationCategoryLBTree = []
            return
          }
          this.QHSEViolationCategoryLBTree = res.data
        })
      },
      getSpecialtyVioClause() {
        getSpecialtyVioClause().then(res => {
          this.violationClauseList = res.data
          const option = this.violationClauseList.find((opt) => opt.description === this.violationClauseValue)
          if (option !== undefined) {
            getSpecialtyVioClauseAssocition({ 'id': option.generalSpecialtyId }).then(res => {
              this.ViolationHSEList = res.data.hse ? res.data.hse : []
              this.ViolationCategoryObsList = res.data.observe ? res.data.observe : []
            })
          }
        })
      },
      handleChangeTime(time, timeString) {
        const enterDate = moment(this.enterTime, 'YYYY-MM-DD HH:mm:ss')
        const differenceInSeconds = enterDate.diff(time, 'seconds')
        const differenceInDays = enterDate.diff(time, 'days')
        if (differenceInSeconds < 0) {
          this.$message.warning('检查时间不能晚于录入时间')
          this.checkTime = enterDate.subtract(1, 'seconds')
          this.form.setFieldsValue({ 'checkDate': this.checkTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T') })
        } else if (differenceInDays > this.$constants.timeInterval) {
          this.$message.warning('检查时间与录入时间不能超过' + this.$constants.timeInterval + '天')
          this.checkTime = enterDate.subtract(1, 'seconds')
          this.form.setFieldsValue({ 'checkDate': this.checkTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T') })
        } else {
          this.form.setFieldsValue({ 'checkDate': timeString.replace(' ', 'T') })
        }
      },
      handleZYZYSelectChange(value, option) {
        this.form.setFieldsValue({
          workType: '',
          location: '',
          workContent: '',
          workRisk: '',
          position: ''
        })
        this.KeyWorkContentList = []
        // console.log('我清理了！')
        this.spc = ''
        if (option) {
          getQHSEKeyWorkTypePage({ 'code': option.data.attrs.code }).then(res => {
            this.KeyWorkTypeList = res.data.rows
          })
          getQHSELocationPage({ 'code': option.data.attrs.code }).then(res => {
            this.LocationList = res.data.rows
          })
          getQHSEPositionPage({ 'code': option.data.attrs.code }).then(res => {
            this.PositionList = res.data.rows
          })
          this.spc = option.data.attrs.code
          this.form.setFieldsValue({ workSpecialtyCode: option.data.attrs.code })
        }
        // const rvtcv = this.form.getFieldValue('violationTypeCategory')
        // if (rvtcv === '专业违章') {
        //   if (this.spc && this.vtc) {
        //     getQHSEXySpecialtyViolation({ 'ViolationTypeCode': this.vtc, 'SpecialtyCode': this.spc }).then(res => {
        //       this.  = res.data.rows
        //       this.form.setFieldsValue({ violationClause: '' })
        //     })
        //   } else {
        //     this.form.setFieldsValue({ violationClause: '' })
        //     this.violationClauseList = []
        //   }
        // }
      },
      handleKeyWorkTypeSelectChange(value, option) {
        this.form.setFieldsValue({
          workContent: '',
          workRisk: ''
        })
        if (option) {
          this.form.setFieldsValue({ keyWorkCode: option.data.attrs.code })
          getQHSEKeyWorkContentPage({ 'code': option.data.attrs.code }).then(res => {
            this.KeyWorkContentList = res.data.rows
          })
        }
      },
      handleKeyWorkContentSelectChange(value, option) {
        if (option) {
          this.form.setFieldsValue({ workRisk: option.data.attrs.rk })
        }
      },
      handleViolationTypeSelectChange(value, option) {
        this.form.setFieldsValue({
          score: 0,
          fine: 0
        })
        if (option) {
          this.form.setFieldsValue({
            score: option.data.attrs.sc,
            fine: option.data.attrs.fine,
            violationTypeCode: option.data.attrs.vtc
          })
        }
      },
      handleViolationCategorySelectChange(val, opt, extra) {
        // console.log(extra)
        if (extra.triggerNode === undefined) {
          this.form.setFieldsValue({ hseElement: '' })
          this.form.setFieldsValue({ observeComm: '' })
          this.form.setFieldsValue({ hseCode: '' })
        } else {
          if (extra.triggerNode._props.dataRef.children.length === 0) {
            const value = extra.triggerNode._props.dataRef.id
            const option = extra.triggerNode._props.title
            if (value) {
              this.violationCategory = option
              this.form.setFieldsValue({ violationCateId: value })
              getQHSEViolationCategoryHSEList({ 'id': value }).then(res => {
                // console.log(res.data.result[0])
                this.form.setFieldsValue({ hseElement: res.data.result[0].item })
                this.form.setFieldsValue({ hseCode: res.data.result[0].code })
                this.ViolationHSEList = res.data.result
              })
              getQHSEViolationCategoryObsList({ 'id': value }).then(res => {
                this.form.setFieldsValue({ observeComm: res.data.result[0].item1 + ';' + res.data.result[0].item2 })
                this.ViolationCategoryObsList = res.data.result
              })
            }
          } else {
            this.violationCategory = ''
            this.form.setFieldsValue({ hseElement: '' })
            this.form.setFieldsValue({ observeComm: '' })
            this.form.setFieldsValue({ hseCode: '' })
            this.$message.error('非正确节点，请重新选择！')
          }
        }
      },
      handleRadioChange(val) {
        // this.form.setFieldsValue({ violationClause: '' })
        // if (this.vtc) {
        //   if (val.target.value === '通用违章') {
        //     getQHSEXyGeneralViolation({ 'ViolationTypeCode': this.vtc }).then(res => {
        //       this.violationClauseList = res.data.rows
        //     })
        //   } else if (val.target.value === '专业违章' && this.spc) {
        //     getQHSEXySpecialtyViolation({ 'ViolationTypeCode': this.vtc, 'SpecialtyCode': this.spc }).then(res => {
        //       this.violationClauseList = res.data.rows
        //     })
        //   } else {
        //     this.violationClauseList = []
        //   }
        // } else {
        //   this.violationClauseList = []
        // }
      },
      handleOrganizationSelectChange(val, opt, extra) {
        if (extra.triggerNode === undefined) {
          this.organizationName = ''
          this.organizationId = ''
        } else {
          if (extra.triggerNode._props.dataRef.children.length === 0) {
            const value = extra.triggerNode._props.dataRef.id
            const option = extra.triggerNode._props.title
            this.organizationName = option
            this.organizationId = value
          } else {
            this.organizationName = ''
            this.organizationId = ''
            this.$message.error('非正确节点，请重新选择！')
          }
        }
      },
      handlefbOrganizationSelectChange(val, opt, extra) {
        // console.log('extra', extra)
        if (extra.triggerNode === undefined) {
          this.contractingUnitName = ''
          this.contractingUnitId = ''
        } else {
          if (extra.triggerNode._props.dataRef.children.length === 0) {
            const value = extra.triggerNode._props.dataRef.id
            const option = extra.triggerNode._props.title
            this.contractingUnitName = option
            this.contractingUnitId = value
          } else {
            this.contractingUnitName = ''
            this.contractingUnitId = ''
            this.$message.error('非正确节点，请重新选择！')
          }
        }
        // console.log(this.contractingUnitName)
      },
      chooseVioClause(item) {
        this.form.setFieldsValue({ violationClause: item.description })
        this.form.setFieldsValue({ description: item.description })
        const chooseWorkClauseCode = item.generalSpecialtyId
        getSpecialtyVioClauseAssocition({ 'id': chooseWorkClauseCode }).then(res => {
          this.violationCategory = res.data.violationCategory
          this.ViolationHSEList = res.data.hse
          this.ViolationCategoryObsList = res.data.observe
          this.form.setFieldsValue({
            violationType: res.data.violationType,
            violationTypeCategory: res.data.violationTypeCategory,
            score: res.data.score,
            fine: res.data.fine,
            observeComm: res.data.observe[0].item1 + ';' + res.data.observe[0].item2,
            hseElement: res.data.hse[0].item,
            violationCateId: res.data.violationCategoryId,
            violationTypeCode: res.data.violationTypeCode,
            hseCode: res.data.hse[0].code
          })
        })
      },
      chooseHse(item) {
        if (item) {
          this.form.setFieldsValue({ hseCode: item.code })
        }
      },
      chooseDepart(item) {
        if (item) {
          this.form.setFieldsValue({ departmentCode: item.code })
        }
      },
      chooseCause(item) {
        if (item) {
          this.form.setFieldsValue({ clauseAnalysisCode: item.code })
        }
      },
      chooseEmp(item) {
        if (item) {
          this.form.setFieldsValue({ employeeTypeCode: item.code })
        }
      },
      choosecheckSpecialty(item) {
        if (item) {
          this.form.setFieldsValue({ checkTypeCode: item.code })
        }
      },
      choosePos(item) {
        if (item) {
          this.form.setFieldsValue({ positionCode: item.positionCode })
        }
        // console.log(item)
      },
      chooseWorkYears(item) {
        if (item) {
          this.form.setFieldsValue({ workYearsCode: item.code })
        }
      },
      chooseAge(item) {
        if (item) {
          this.form.setFieldsValue({ ageCode: item.code })
        }
      },
      chooseConsequence(item) {
        if (item) {
          this.form.setFieldsValue({ consequencesCode: item.code })
        }
      },
      chooseLoc(item) {
        if (item) {
          this.form.setFieldsValue({ locationCode: item.locationCode })
        }
      },
      QHSEXyCorssViolationDetail(text) {
        QHSEXyCorssViolationDetail(text).then((res) => {
          // console.log('res:', res)
          // setTimeout(() => {
          this.form.setFieldsValue({
            // 违章ID
            qhseXyViolationId: res.data.qhseXyViolationId,
            // 检查人员ID
            userId: res.data.userId,
            // 检查人员姓名
            userName: res.data.userName,
            // 检查时间
            checkDate: res.data.checkDate,
            // 录入时间
            enterTime: res.data.enterTime ? res.data.enterTime : undefined,
            // 数据来源
            enterSys: res.data.enterSys,
            // 检查类型
            check_Type: res.data.check_Type,
            // 作业项目
            workItem: res.data.workItem,
            // 关键作业内容
            workContent: res.data.workContent,
            // 作业风险等级
            workRisk: res.data.workRisk,
            // 关键作业类型
            workType: res.data.workType,
            // 作业专业
            workSpecialty: res.data.workSpecialty,
            // 位置区域
            location: res.data.location,
            // 描述
            description: res.data.description,
            // 违章性质
            violationType: res.data.violationType,
            // 违章类别
            // 违章性质分类
            violationTypeCategory: res.data.violationTypeCategory,
            // 违章条款
            violationClause: res.data.violationClause,
            // 体系要素
            hseElement: res.data.hseElement,
            // 安全沟通
            observeComm: res.data.observeComm,
            // 原因分析
            causeAnalysis: res.data.causeAnalysis,
            // 归属直线部门
            directDepartment: res.data.directDepartment,
            // 可能后果
            potentialConsequence: res.data.potentialConsequence,
            // 相关方人员ID
            violationUserId: res.data.violationUserId,
            // 相关方人员姓名
            violationUserName: res.data.violationUserName,
            // 相关方人员单位名称
            violationUserDepart: res.data.violationUserDepart,
            // 工号/身份证号
            erp: res.data.erp,
            // 年龄
            age: res.data.age,
            // 工龄
            workYears: res.data.workYears,
            // 用工性质
            employeeType: res.data.employeeType,
            // 违章岗位
            position: res.data.position,
            // 记分
            score: res.data.score,
            // 罚款
            fine: res.data.fine,
            // 图片（不用）
            pic: res.data.pic,
            // 违章类别id
            violationCateId: res.data.violationCateId,
            // 检查类型code
            checkTypeCode: res.data.checkTypeCode,
            // 关键作业Code
            keyWorkCode: res.data.keyWorkCode,
            // 作业专业Code
            workSpecialtyCode: res.data.workSpecialtyCode,
            // 违章性质code
            violationTypeCode: res.data.violationTypeCode,
            // 体系要素code
            hseCode: res.data.hseCode,
            // 归属部门code
            departmentCode: res.data.departmentCode,
            // 原因分析code
            clauseAnalysisCode: res.data.clauseAnalysisCode,
            // 用工性质code
            employeeTypeCode: res.data.employeeTypeCode,
            // 工龄code
            workYearsCode: res.data.workYearsCode,
            // 年龄code
            ageCode: res.data.ageCode,
            // 可能后果code
            consequencesCode: res.data.consequencesCode,
            // 违章岗位code
            positionCode: res.data.positionCode,
            // 位置区域code
            locationCode: res.data.locationCode,
            // 人员的检查单位id
            checkOrganizationId: res.data.checkOrganizationId
          })
          // }, 1)
          this.workSpecialtyValue = this.form.getFieldValue('workSpecialty')
          this.violationTypeValue = this.form.getFieldValue('violationType')
          this.workTypeValue = this.form.getFieldValue('workType')
          this.violationClauseValue = this.form.getFieldValue('violationClause')
          this.violationUserId = this.form.getFieldValue('violationUserId')
          this.checkTime = moment(this.form.getFieldValue('checkDate'))
          this.enterTime = this.form.getFieldValue('enterTime') ? this.form.getFieldValue('enterTime').replace('T', ' ') : undefined
          // console.log('violationUserId123', this.violationUserId)
          // 违章类别
          this.violationCategory = res.data.violationCategory
          // 被检查单位id
          this.organizationId = res.data.organizationId
          // 被检查单位名称
          this.organizationName = res.data.organizationName
          this.contractingUnitName = res.data.contractingUnitName
          this.contractingUnitId = res.data.contractingUnitId
          this.files = res.data.files
          // 在组件创建时，将 files 数组转换为 uploadFileList 数组
          this.fileList = this.files.map((file, index) => {
            const suffix = file.name.split('.').pop()
            return {
              uid: `file-${index}`,
              name: file.name,
              status: 'done',
              url: `data:image/${suffix};base64,${file.base64Content}`,
              thumbUrl: ''
            }
          })
          return res.data
        })
      },
      queryDetail(record) {
        const param = { 'id': record.qhseXyViolationId }
        this.QHSEXyCorssViolationDetail(param)
      },
      // 初始化方法
      edit(record) {
        this.queryDetail(record)
        // console.log('--this is record from edit--', record)
        this.confirmLoading = true
        this.visible = true
        this.getUnitTree()
        this.getCheckTypeList()
        this.getQHSEOrganizationTree()
        this.getQHSEViolationCategoryLBTree()
        this.getQHSEGSBMList()
        this.getQHSEKNHGList()
        this.getQHSEYYFXList()
        this.getQHSEYGXZList()
        this.getQHSEAgeList()
        this.getQHSEGLList()
        this.getQHSEKeyWorkSpecialtyList()
        this.getQHSEXyViolationTypeList()
        // this.getQHSEViolationHSEList()
        this.getSpecialtyVioClause()
        // 基本信息加人表单
        this.confirmLoading = false
      },
      handleSubmit() {
        const {
          form: { validateFields }
        } = this
        this.confirmLoading = true
        validateFields(async (errors, values) => {
          if (!errors && this.violationCategory && typeof this.violationCategory !== 'undefined' && this.violationCategory !== '' &&
            this.organizationId && typeof this.organizationId !== 'undefined' &&
            this.organizationId !== '' && this.organizationName && typeof this.organizationName !== 'undefined' && this.organizationName !== '' &&
            this.contractingUnitName !== '' && typeof this.contractingUnitName !== 'undefined' &&
            this.contractingUnitId !== '' && typeof this.contractingUnitId !== 'undefined') {
            if (!this.valId) {
              this.$message.error('身份证号格式错误')
              this.confirmLoading = false
              return
            }
            values.violationCategory = this.violationCategory
            values.organizationId = this.organizationId
            values.organizationName = this.organizationName
            values.contractingUnitName = this.contractingUnitName
            values.contractingUnitId = this.contractingUnitId
            values.files = this.files
            values.updataTime = moment().format('YYYY-MM-DDTHH:mm:ss')
            values.updateBy = this.userInfo.realName
            QHSECrossViolationEdit(values)
              .then((res) => {
                if (res.success && res.code === 200) {
                  this.$message.success('编辑成功')
                  this.confirmLoading = false
                  this.$emit('ok', values)
                  this.handleCancel()
                } else {
                  this.$message.error('编辑失败：' + res.message)
                }
              })
              .finally((res) => {
                this.confirmLoading = false
              })
          } else {
            // console.log('values', values)
            this.confirmLoading = false
            this.$message.warning('信息尚未完善，请完善后再提交')
          }
        })
      },
      handleCancel () {
        this.form.resetFields()
        this.violationUserId = null
        // console.log('violationUserId：', this.violationUserId)
        this.visible = false
        // 清理子表单中数据
        this.data = []
      },
      handleModalCancel() {
        this.Modalvisible = false
      },
      chooseVioPeople(userName, userId, unitName, employeeNo) {
        // console.log('收到了username=' + userName)
        // console.log('收到了userid=' + userId)
        // console.log('收到了unitname=' + userDeptId)
        const parts = unitName.split('/')
        this.form.setFieldsValue({
          violationUserName: userName,
          violationUserId: userId,
          violationUserDepart: parts[parts.length - 1],
          erp: employeeNo
        })
        this.violationUserId = userId
        this.Modalvisible = false
        getViolationUserNameKid({ 'id': userId }).then(res => {
          this.form.setFieldsValue({
            age: res.data.age ? res.data.age : this.form.getFieldValue('age'),
            ageCode: res.data.ageCode ? res.data.ageCode : this.form.getFieldValue('ageCode'),
            workYears: res.data.workYears ? res.data.workYears : this.form.getFieldValue('workYears'),
            workYearsCode: res.data.workYearsCode ? res.data.workYearsCode : this.form.getFieldValue('workYearsCode'),
            employeeType: res.data.employeeType ? res.data.employeeType : this.form.getFieldValue('employeeType'),
            position: res.data.position ? res.data.position : this.form.getFieldValue('position'),
            positionCode: res.data.positionCode ? res.data.positionCode : this.form.getFieldValue('positionCode'),
            employeeTypeCode: res.data.employeeTypeCode ? res.data.employeeTypeCode : this.form.getFieldValue('employeeTypeCode')
          })
        })
      }
    }
  }
</script>
<style scoped>
  *[disabled] {
    color: black;
    background-color: whitesmoke;
    cursor: not-allowed;
    opacity: 0.5;
  }
  .spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 48px;
    height: 48px;
    animation: spin 2s linear infinite;
    margin: 20px auto;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
</style>
